# -*- coding: utf-8 -*-
# @Time    : 2018-03-01 19:04
# @Author  : M-修改指标
# @Email   : yangfeng@bbdservice.com
# @File    : Rule26_Ind_UnPaidOverdueCnt_3YrTO5YrCheck.py
# @Software: PyCharm


'''eof
name:申请人3-5年内未结清贷款、贷记卡、准贷记卡逾期次数及期数校验
code:Ind_UnPaidOverdueCnt_3YrTO5YrCheck
tableName:
columnName:
groups:准入>个人征信
dependencies:IC
type:常用指标
datasourceType:在线指标
description:
eof'''

import sys
import json
import re
import datetime
reload(sys)
sys.setdefaultencoding('utf-8')

null_type_list = ['', None, 'null', '/', 'Null']

def FormatData(tableName):
    try:
        icr = json.loads(IC[0]["icr"])[tableName]
        return icr if isinstance(icr, list) and len(icr) > 0 else [{}]
    except:
        return [{}]


def ConvertDataType(dataValue, dataType):
    returnData = None
    if dataType == 'float':
        try:
            returnData = float(dataValue) if float(dataValue) >= 0 else None
        except:
            returnData = None
    elif dataType == 'None':
        returnData = 0 if dataValue is None else dataValue
    return returnData


def IndUnPaidOverdueCnt3YrTO5YrCheckPre(*arg):
    try:
        returnList = []
        twoYearAgo = (datetime.datetime.now().year - 2) * 12 + datetime.datetime.now().month
        fiveYearAgo = (datetime.datetime.now().year - 5) * 12 + datetime.datetime.now().month
        icrLoanInfo002LoanList = FormatData(arg[0])
        icrLatest5YearOverdueDetailLoanList = FormatData(arg[1])
        if icrLoanInfo002LoanList == [{}] or icrLatest5YearOverdueDetailLoanList == [{}]:
            returnList.append(None)
        else:
            icrLatest5YearOverdueDetailLoanDict = {}
            for icrLatest5YearOverdueDetailLoan in icrLatest5YearOverdueDetailLoanList:
                try:
                    account = icrLatest5YearOverdueDetailLoan.get('Account')
                    month = re.compile(r'\D+').sub('', icrLatest5YearOverdueDetailLoan.get('Month'))
                    amount = ConvertDataType(icrLatest5YearOverdueDetailLoan.get('Amount'), 'float')
                    lastMonths = ConvertDataType(icrLatest5YearOverdueDetailLoan.get('LastMonths'), 'float')
                    if account in null_type_list or month in null_type_list or amount in null_type_list \
                            or lastMonths in null_type_list:
                        continue
                    monthFact = float(month[:4]) * 12 + float(month[4:6]) if float(month[4:6]) <= 12 else float(month[4:5])
                    row = {"month": monthFact, "amount": amount, "lastMonths": lastMonths}
                    if icrLatest5YearOverdueDetailLoanDict.has_key(account):
                        accountAdd = icrLatest5YearOverdueDetailLoanDict[account]
                        accountAdd.append(row)
                        icrLatest5YearOverdueDetailLoanDict.update({account: accountAdd})
                    else:
                        icrLatest5YearOverdueDetailLoanDict.setdefault(account, [row])
                except:
                    continue

            for icrLoanInfo002Loan in icrLoanInfo002LoanList:
                try:
                    state = icrLoanInfo002Loan.get('State')
                    account = icrLoanInfo002Loan.get('Account')
                    if state in null_type_list or account in null_type_list or account not in icrLatest5YearOverdueDetailLoanDict.keys():
                        returnList.append(None)
                        continue
                    if ((arg[0] == "ICRLoanInfo002*Loan" and state in [u"正常", u"逾期", u"呆账"])
                        or (arg[0] == "ICRLoancardInfo002*Card" and state in [u"正常", u"冻结", u"止付", u"呆账"])
                        or (arg[0] == "ICRStdLoancardInfo002*Std" and state in [u"正常", u"冻结", u"止付", u"呆账"])):
                        rowDatas = icrLatest5YearOverdueDetailLoanDict[account]
                        for rowData in rowDatas:
                            lastMonthsDel = rowData['lastMonths']-2 if arg[0] == "ICRStdLoancardInfo002*Std" else rowData['lastMonths']
                            if lastMonthsDel >= 4 and ((arg[0] == "ICRLoanInfo002*Loan" and rowData['amount'] > 1000)
                                    or (arg[0] in ("ICRLoancardInfo002*Card", "ICRStdLoancardInfo002*Std") and rowData['amount'] > 500)) \
                                    and rowData['month'] <= twoYearAgo and rowData['month'] > fiveYearAgo:
                                returnList.append(1)
                            else:
                                returnList.append(0)
                    else:
                        returnList.append(0)
                except:
                    returnList.append(None)
                    continue
        return returnList
    except:
        return None


def IndUnPaidOverdueCnt3YrTO5YrCheck():
    returnList1 = IndUnPaidOverdueCnt3YrTO5YrCheckPre(*("ICRLoanInfo002*Loan", "ICRLatest5YearOverdueDetail*Loan"))
    returnList2 = IndUnPaidOverdueCnt3YrTO5YrCheckPre(*("ICRLoancardInfo002*Card", "ICRLatest5YearOverdueDetail*Card"))
    returnList3 = IndUnPaidOverdueCnt3YrTO5YrCheckPre(*("ICRStdLoancardInfo002*Std", "ICRLatest5YearOverdueDetail*Std"))
    returnList = (returnList1 if returnList1 is not None else []) \
               + (returnList2 if returnList2 is not None else []) \
               + (returnList3 if returnList3 is not None else [])
    returnListNotNone = filter(lambda x:x is not None, returnList)
    if len(returnListNotNone) == 0:
        return u"缺失值"
    else:
        return sum(returnListNotNone)


result = IndUnPaidOverdueCnt3YrTO5YrCheck()